package com.xgst.land.activity

import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.githang.statusbar.StatusBarCompat
import com.gym.baselib.base.BaseActivity
import com.hjq.http.EasyConfig
import com.ht.medicaltreatment.base.CacheKey
import com.xgst.land.R
import com.xgst.land.databinding.ActivityLoginLayoutBinding
import com.xgst.land.utils.ProgressUtils.showProgress
import com.xgst.land.viewmodel.LoginViewModel

class LoginActivity : BaseActivity<ActivityLoginLayoutBinding>() {

    private lateinit var videModel:LoginViewModel

    override fun viewBinding(): ActivityLoginLayoutBinding {
        return ActivityLoginLayoutBinding.inflate(layoutInflater)
    }

    override fun init() {
        StatusBarCompat.setTranslucent(window, true)
        videModel = ViewModelProvider(this)[LoginViewModel::class.java]
        val ip = SPStaticUtils.getString(CacheKey.IP)
        val port = SPStaticUtils.getString(CacheKey.PORT)
        if(port.isNotEmpty()){
            binding.etPort.setText(port)
        }
        if(ip.isNotEmpty()){
            binding.tvIP.setText(ip)
        }else{
            SPStaticUtils.put(CacheKey.IP,"59.110.162.243")
            SPStaticUtils.put(CacheKey.PORT,"8080")
        }

        val name = SPStaticUtils.getString(CacheKey.USERNAME)
        val psw = SPStaticUtils.getString(CacheKey.PASSWORD)
        binding.etAccount.setText(name)
        binding.etPSW.setText(psw)
        binding.login.setOnClickListener {
            val ip = binding.tvIP.text.toString()
            val port = binding.etPort.text.toString()
            if(ip.isNotEmpty() && port.isNotEmpty()){
                SPStaticUtils.put(CacheKey.IP,ip)
                SPStaticUtils.put(CacheKey.PORT,port)
            }else{
                showToast("请输入ip地址和端口号")
                return@setOnClickListener
            }
            videModel.checkPermission({
                val account = binding.etAccount.text.toString()
                val psw = binding.etPSW.text.toString()
                if(account == "" || psw == ""){
                    showToast("请填写账号/密码")
                    return@checkPermission
                }
                showProgress()
                videModel.login(account,psw,{
                    dismissProgress()
                    SPStaticUtils.put(CacheKey.USERNAME,account)
                    SPStaticUtils.put(CacheKey.PASSWORD,psw)
                    SPStaticUtils.put(CacheKey.MAIN_NAME,it.data.chineseName)
                    SPStaticUtils.put(CacheKey.NAME,it.data.name)
                    SPStaticUtils.put(CacheKey.TOKEN,it.data.token)
                    EasyConfig.getInstance().addHeader("Mobile-Custom-Token", it.data.token)
                    startActivity(MainActivity::class.java)
                    finish()
                })
            })
        }
    }

}